import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {RootStackParamList} from '../../Nav/routes';
import {
  ActivityIndicator,
  Dimensions,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import {useCallback, useEffect, useState} from 'react';
import React from 'react';
import {
  primaryBackgroundColor,
  secondaryBorderColor,
  primaryColor2,
  inputBackgroundColor,
  primaryColor3,
  primaryColor,
} from '../../../theme/default';
import {useRegister} from '../../../hooks/useRegister';
import {Card, CardModel} from '../../../db/models/cardModel';
import {
  generatePasskeyTitle,
  hashString,
  parseShortCardNumber,
} from '../../../utils';
import {useIdentityProvider} from '../../../hooks/useSIWPIdentity';
import {DEFAULT_DISPLAY_NAME} from '../../../constants';
import {useNavigation} from '@react-navigation/native';
import {useCardListProvider} from '../../../hooks/useCardListProvider';
import {useTranslation} from 'react-i18next';
import Toast from 'react-native-toast-message';

type CreateWalletProp = {
  cardNumber: string;
  cardTokenized: any;
  type?: string; // 'init' | 'common'
};

const {width} = Dimensions.get('window');

export default function CreateCardWallet({
  cardNumber,
  cardTokenized,
  type,
}: Readonly<CreateWalletProp>) {
  const [loading, setLoading] = useState<boolean>(false);
  const [startConfirm, setStartConfirm] = useState<boolean>(false);
  const {registerUsername, error} = useRegister();
  const {loginStatus, login} = useIdentityProvider();
  const [displayName, setDisplayName] = useState(
    `${DEFAULT_DISPLAY_NAME} - ${parseShortCardNumber(cardNumber)}`,
  );

  const {t} = useTranslation();

  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const {getCards} = useCardListProvider();

  useEffect(() => {
    if (error != '') {
      Toast.show({
        type: 'error',
        text1: t('registerTitle'),
        text2: error,
        position: Platform.OS === 'android' ? 'top' : 'bottom',
      });
    }
  }, [error]);

  useEffect(() => {
    if (startConfirm && loginStatus == 'success' && type == 'addCard') {
      getCards();
      navigation.pop(2);
    }
  }, [loginStatus, type, startConfirm]);

  const handleCreateWallet = useCallback(async () => {
    console.log('loading_useCallback界面', loading);
    console.log('displayName', displayName);
    if (loading) {
      return;
    }
    if (displayName == '') {
      return;
    }
    try {
      setLoading(true);
      const cardModel = new CardModel();
      const tmpCard = await cardModel.getByCardNumber(cardNumber);
      console.log('tmpCard，我的卡', tmpCard);
      if (tmpCard != null) {
        await login(tmpCard.userName);
      } else {
        console.log('cardNumber数字', cardNumber);
        // const scheme = (cardTokenized['scheme'] as string).toUpperCase();
        const scheme = 'worknet';
        const hash = hashString(`${scheme}:${cardNumber}`);
        const userName = `up:${scheme}:${hash}`;
        console.log('userName', userName);
        const response = await registerUsername({
          userName: userName,
          passkeyTitle: generatePasskeyTitle(displayName),
          displayName: displayName,
        });
        console.log('response', response);
        if (response == null) {
          //
          console.log('Register failed.');
          setLoading(false);
          return;
        }

        const card: Card = {
          cardNumber: cardNumber,
          userName: userName,
          cardType: cardTokenized['card_type'],
          issuer: cardTokenized['issuer'],
          issuerCountry: cardTokenized['issuer_country'],
          scheme: cardTokenized['scheme'],
          createdAt: CardModel.getCreatedAt(),
          isBind: 0,
        };
        await cardModel.save(card);
        setStartConfirm(true);
        await login(response);
      }
    } catch (error) {
      setLoading(false);
    }
  }, [cardNumber, displayName]);

  // useEffect(() => {
  //   setDisplayName(
  //     `${DEFAULT_DISPLAY_NAME} - ${parseShortCardNumber(cardNumber)}`,
  //   );
  // }, [cardNumber]);

  useEffect(() => {
    if (startConfirm && loginStatus != 'logging-in') {
      getCards();
      setLoading(false);
    }
  }, [loginStatus, startConfirm]);

  return (
    <View style={styles.container}>
      <View style={styles.context}>
        <View style={{marginBottom: 3}}>
          <Text style={styles.inputTitle}>{t('walletName')}</Text>
        </View>
        <TextInput
          autoCapitalize="none"
          value={displayName}
          onChangeText={setDisplayName}
          style={styles.displayName}></TextInput>

        <TouchableOpacity style={styles.button} onPress={handleCreateWallet}>
          {loading && (
            <ActivityIndicator
              size="small"
              color={primaryColor}
              style={{marginRight: 4}}></ActivityIndicator>
          )}
          <Text style={styles.buttonText}>{t('creatWallet')}</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: primaryBackgroundColor,
  },
  context: {
    width: width - 32,
    backgroundColor: primaryBackgroundColor,
    alignItems: 'flex-start',
    justifyContent: 'flex-start',
    paddingLeft: 16,
    paddingRight: 16,
    paddingTop: 24,
    paddingBottom: 24,
    marginTop: 16,
    marginBottom: 16,
    borderColor: secondaryBorderColor,
    borderWidth: 1,
    borderRadius: 12,
  },
  displayName: {
    fontSize: 16,
    height: 48,
    color: primaryColor2,
    backgroundColor: inputBackgroundColor,
    borderColor: secondaryBorderColor,
    borderRadius: 12,
    borderWidth: 1,
    width: '100%',
    paddingLeft: 12,
    paddingRight: 12,
  },
  inputTitle: {
    color: primaryColor3,
    marginLeft: 12,
    marginBottom: 3,
    fontSize: 13,
    fontWeight: '600',
  },
  button: {
    width: '100%',
    marginTop: 24,
    marginBottom: 24,
    height: 44,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 12,
    borderColor: secondaryBorderColor,
    borderWidth: 1,
    backgroundColor: secondaryBorderColor,
    flexDirection: 'row',
  },
  buttonText: {
    color: primaryColor2,
    fontSize: 16,
  },
});
